<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container" style="margin-bottom:20px">
      <span style="margin-left:10px">学校名称：</span>
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="请输入学校名称" v-model="listQuery.title">
      </el-input>
      <span style="margin-left:10px">所属地区：</span>
      <el-cascader
           change-on-select clearable placeholder="全部" expand-trigger="click"
          :options="areas"
          v-model="areaOption"
        ></el-cascader>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="success" icon="el-icon-plus">新增</el-button>
    </div>

    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="数据加载中，请稍后" border fit highlight-current-row  style="width: 100%">
      <el-table-column  v-if='showAllDel' type="selection" width="55">
      </el-table-column>

      <el-table-column min-width="160" align="center" label="ID" prop="id"></el-table-column>

      <el-table-column min-width="160" align="center" label="学校名称" prop="title"></el-table-column>

      <el-table-column min-width="160" align="center" label="学校类型" prop="typeDesc"></el-table-column>

      <el-table-column min-width="160" align="center" label="状态" prop="statusDesc"></el-table-column>

      <el-table-column min-width="160" align="center" label="所属地区" prop="areaNames" show-overflow-tooltip></el-table-column>

      <el-table-column align="center" label="操作" min-width="240">
        <template slot-scope="scope">
          <el-button size="small" type="primary" @click="handleOprate(scope.row)" v-if="scope.row.deleted == 0">无效</el-button>
          <el-button size="small" type="primary" @click="handleOprate(scope.row)" v-else>有效</el-button>
          <el-button size="small" @click="handleUpdate(scope.row)">编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNo"
        :page-sizes="[10,20,30,50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="dialogStatus=='create' ? '新增学校' : '编辑学校'" :visible.sync="dialogFormVisible" center v-if="dialogFormVisible">
      <el-form :model="temp" :rules="rules" ref="ruleForm">
        <el-form-item label="学校名称" label-width="80px" prop="title">
          <el-input v-model="temp.title" auto-complete="off" maxlength="20"
          placeholder="请输入学校名称（不超过20个字）"></el-input>
        </el-form-item>
        <el-form-item label="所属地区" label-width="80px" prop="areaIds" v-if="temp.type == 5">
          <el-cascader
            change-on-select
            expand-trigger="click"
            :options="areas"
            v-model="temp.areaIds"
            @blur="handleChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="所属地区" label-width="80px" prop="areaIds" v-if="temp.type == 4">
          <el-cascader
            expand-trigger="click"
            :options="areas"
            v-model="temp.areaIds"
            @blur="handleChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="学校类型" label-width="80px" prop="type">
          <el-select v-model="temp.type" placeholder="请选择" disabled>
            <el-option key="4" label="高中" :value="4"></el-option>
            <el-option key="5" label="大学" :value="5"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学校简介" label-width="80px" prop="briefDesc">
          <el-input style="min-width:480px" placeholder="请输入学校简介(最多140个字)" maxlength="140" v-model="temp.briefDesc" type="textarea" :autosize="{ minRows: 4, maxRows: 4}" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="addForm">确 定</el-button>
        <el-button v-else type="primary" @click="updateForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, getAreaList, getSchoolsById, update, getId, add, toggleId } from '@/api/school'
// import { getToken } from '@/utils/auth' // 验权
export default {
  name: 'list',
  data() {
    return {
      areaValue:'',
      dialogStatus:'create',
      schools:[],
      areas:[],
      areasAll:[],
      schoolOption:0,
      areaOption: [''],
      version:[],
      userTypes:[],
      temp: {},
      inputVisible:false,
      inputValue:'',
      dateformat:'',
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        'pageNo': 1,
        'pageSize': 10,
        'areaId':'',
        'title':''
      },
      dialogFormVisible: false,
      rules: {
        title: [{ required: true, message: '请输入学校名称', trigger: 'blur' }],
        areaIds: [{ required: true, message: '请选择所属地区', trigger: 'change' }],
        schoolId: [{ required: true, message: '请选择所属学校', trigger: 'change' }],
        type: [{ required: true, message: '请选择学校类型', trigger: 'change' }]
      },
      tableKey: 0,
      showAllDel:false,
      multipleSelection:[],
      pageBoolean:{
        delColor:'primary',
        delText:'批量删除'
      }
    }
  },
  mounted() {
    this.getList()
    this.fetchAreaData()
  },
  filters: {
    statusFilter(status) {
      const statusMap = { '1':'学生', '2':'家长' }
      return statusMap[status]
    }
  },
  methods: {
    handleOprate(row){
      toggleId({ id:row.id, operateType:row.deleted == 0 ? 1 : 0 }).then(res => {
        const { code } = res
        if(code == 0){
          this.$notify({
            message: `${row.deleted == 0 ? '无效' : '有效'}成功`,
            type: 'success',
            duration: 2000
          })
          row.statusDesc = row.deleted == 0 ? '无效' : '有效'
          if(row.deleted == 0){
            row.deleted = 1
          }else{
            row.deleted = 0
          }
        }
      })
    },
    handleChange(e) {
      let areaValue = e.target.defaultValue
      if(areaValue.length > 0){
        areaValue = areaValue.replace(/\//g, '-')
      }
      this.areaValue = areaValue
    },
    // fetchSchoolData(id, type) {
    //   getSchoolsById(id).then(response => {
    //     this.schools = response.data
    //     if(type == 1){
    //       this.dialogFormVisible = true
    //     }else{
    //       this.schoolOption = response.data[0]['schoolId']
    //     }
    //   })
    // },
    fetchAreaData() {
      getAreaList().then(response => {
        const areas = response.data
        const areasAll = [{ label:'全部', value:'', children:null }, ...areas]
        this.areas = areas
        this.areasAll = areasAll
      })
    },
    getList() {
      this.listLoading = true
      const params = this.listQuery
      getList(params).then(response => {
        const { code, data:{ total, list } } = response
        if(code == 0){
          this.total = total
          this.list = list
          this.listLoading = false
        }
      })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.listQuery.areaId = this.areaOption[this.areaOption.length - 1]
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNo = val
      this.getList()
    },
    handleCreate() {
      this.temp = {
        type:4
      }
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    handleUpdate(row) {
      this.dialogStatus = 'update'
      getId(row.id).then(response => {
        const { code, data } = response
        if(data['areaIds'].length != 0){
          const { areas } = this
          const areaOption = data['areaIds'].split(',').map(e => e = parseInt(e))
          data['areaIds'] = areaOption
          this.getNameForId(areaOption, areas, 0, [])
        }
        data['briefDesc'] = data['briefDesc']
        this.temp = data
        this.dialogFormVisible = true
      })
    },
    getNameForId(areaOption, areas, index, names){
      if(!areaOption[index]){
        this.areaValue = names.join('-')
        return
      }
      areas.map(e => {
        if(e.value == areaOption[index]){
          const areaNew = e.children
          index += 1
          names.push(e.label)
          return this.getNameForId(areaOption, areaNew, index, names)
        }
      })
    },
    addForm() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          const { temp } = this
          temp['areaId'] = temp['areaIds'][temp['areaIds'].length - 1]
          add(temp).then(response => {
            const { code, message } = response
            if(code == 0){
              this.getList()
              this.dialogFormVisible = false
            }else{
              this.$message(message)
            }
          })
        } else {
          return false
        }
      })
    },
    updateForm() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          const { temp } = this
          const params = {}
          params['id'] = temp['id']
          params['briefDesc'] = temp['briefDesc']
          params['areaId'] = temp['areaIds'][temp['areaIds'].length - 1]
          params['title'] = temp['title']
          params['type'] = temp['type']
          update(params).then(response => {
            const { code } = response
            if(code == 0){
              this.list.map((e, i) => {
                if(e.id === temp.id){
                  if(this.areaValue.length > 0){
                    temp['areaNames'] = this.areaValue
                  }
                  const newTemp = Object.assign({}, e, temp)
                  this.list.splice(i, 1, newTemp)
                }
              })
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleDelete(idx, row) {
      const { id } = row
      delId(id).then(response => {
        const { code } = response
        if(code == 0){
          this.$notify({
            title: '成功',
            message: '删除资讯成功',
            type: 'success',
            duration: 2000
          })
          const index = this.list.indexOf(idx)
          this.list.splice(idx, 1)
          this.total--
        }else{
          this.$notify({
            title: '失败',
            message: '删除资讯失败',
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    handleRefresh() {
      this.list = null
      this.total = null
      this.listQuery.pageNo = 1
      this.getList()
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.icon-ctx{
  width:160px;
  height:80px;
  overflow:hidden;
  margin:0 auto;
}
.el-tag + .el-tag {
    margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.app-container{
  padding:20px;
}
.pagination-container{
  margin-top:30px;
}
</style>
